package com.pay.wechat.handler;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.pay.common.pay.constant.Constant;
import com.pay.wechat.builder.TextBuilder;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class MsgHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地86
        }
        // 微信接收到的用户发送的信息
        String message = wxMessage.getContent();
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("key", "free"); // 类似qq密码
        paramMap.put("appid", "0"); // 终生不可改变
        paramMap.put("msg", message);
        
        try {
            String result = HttpUtil.get("http://api.qingyunke.com/api.php", paramMap);
            logger.info("result:{}",result);
            if (StringUtils.isEmpty(result)) {
                return serResult("系统忙,请稍后重试!", wxMessage,weixinService);
            }
            
            JSONObject json = JSONObject.parseObject(result);
            Integer code = json.getInteger("result");
            if (!code.equals(Constant.QINGYUNKE_RESULT_OK)) {
                return serResult("系统忙,请稍后重试!", wxMessage,weixinService);
            }
            
            // 接口调用成功 获取 智能化接口中响应的内容
            String msg = json.getString("content");
            return serResult(msg, wxMessage,weixinService);
        } catch (Exception e) {
            logger.info("e:{}",e);
            return serResult("系统忙,请稍后重试!", wxMessage,weixinService);
        }
        
    }
    
    private WxMpXmlOutMessage serResult(String content, WxMpXmlMessage wxMessage,
                                    WxMpService service ){
        return new TextBuilder().build(content, wxMessage, service);
    }

}
